/**
 * Created by liyongliang on 15/8/27.
 */
(function(root){
    // Creates namespaced functions within a closure.
    //
    // http://github.com/jweir/namespace
    // Copyright (c) 2011 John Weir john@famedriver.com

    function namespace(moduleNamespace, functions) {
        var space, i;

        if (typeof arguments[0] != "string"){
            space = root;
            i = 0;
        } else {
            space = namespaceFor(arguments[0].split("."));
            i = 1;
        }

        for (var l = arguments.length; i < l; i++) {
            space[functionName(arguments[i])] = arguments[i];
        }
    }

    function functionName(fn) {
        return fn.name || fn.toString().match(/^\s*function\s+([^\s\(]+)/)[1];
    }

    function namespaceFor(parts) {
        var space = root;

        for (var i=0; i < parts.length; i++) {
            space = space[parts[i]] = space[parts[i]] || {};
        }
        return space;
    }

    namespace(namespace);
}(this)); // <- change this if you want to change the scope of namespace

;(function($){
    $.extend($.fn, {
        lazyload: function(){
            var imgs = this;
            function getHeight() {
                return window.innerHeight || screen.availHeight;
            }

            function inViewport(el) {
                var height = getHeight();
                var min = window.pageYOffset - height / 2;
                var max = getMax();
                min = min < 0 ? 0 : min;
                var elTop = el.offset().top;
                return elTop > 0  && elTop >= min && elTop <= max;
            }
            function getMax() {
                return window.pageYOffset + getHeight() * 1.2;
            }
            function load(_self) {

                if (_self.attr('loaded')) return;
                var img = new Image(),
                    url = _self.attr('_src') || _self.data('src');

                img.onload = function() {
                    _self.attr('src', url).removeClass('lazy');
                    var opacity = 1;
                    if (_self.attr("_opacity")) {
                        opacity = _self.css("opacity");
                    }
                    _self.css({
                        "transition": "360ms",
                        "opacity": opacity
                    });
                }
                url && (img.src = url);
                _self.attr('loaded', true);
            }


            var loadIndex = 0;
            var prevTime = new Date().getTime();

            $(window).on('scroll.lazyload',function(e){

                var curTime = new Date().getTime();

                if (curTime - prevTime < 100) {
                    return;
                }
                var oldIndex = loadIndex;
                loadIndex++;
                prevTime = curTime;
                var lazys = imgs;
                var height = 120;
                var rad = parseInt(Math.random() * 10) % 2 == 0;
                var length = lazys.length;

                for (var i = 0; i < length; i++) {

                    if (oldIndex + 1 != loadIndex) {
                        break;
                    }
                    var node = lazys[i];

                    var Qme = $(imgs[i]);

                    if (Qme.offset().top > getMax()) {

                        break;
                    }
                    var opacity = parseFloat(Qme.css("opacity")) || 0;

                    opacity <= 0 ? Qme.css("opacity", "0.5") : Qme.attr("_opacity", true);

                    if (inViewport(Qme)) {
                        load(Qme);
                    }
                }

            });
            setTimeout(function(){
                $(window).trigger('scroll');
            },100)

            // `this` refers to the current Zepto collection.
            // When possible, return the Zepto collection to allow chaining.
            ///return this.html('bar')
        }
    })
})(Zepto);

(function () {

    var getParam = function(name){
        var search = document.location.search;
        var pattern = new RegExp("[?&]"+name+"\=([^&]+)", "g");
        var matcher = pattern.exec(search);
        var items = null;
        if(null != matcher){
            try{
                items = decodeURIComponent(decodeURIComponent(matcher[1]));
            }catch(e){
                try{
                    items = decodeURIComponent(matcher[1]);
                }catch(e){
                    items = matcher[1];
                }
            }
        }
        return items;
    };

    Handlebars.registerHelper("addOne", function (index) {
        return index + 1;
    });

    namespace('CT.util', Request);

    function Request(keyword, callback) {
        $.ajax({
            data: {
                parameters: '{common:{},data:{keyword:"' + keyword + '"}}'
            },
            url: 'http://www.one-dao.com/api/group/oneDayEscape/byCity?callback=?',
            success: function(json){
                callback && callback(json);
            },
            error: function(xhr) {}
        })
    }

    namespace('CT.app', renderList, initPlacePage);

	var cityName = getParam('city') || '';

	$('.city-name').removeClass('hide').html(cityName);

    var $list = $('#js-list');

    function renderList(json) {

        if (json.code === 1) {
            if (json.data.groupList.length > 0) {
                var renderTemplate = $('#renderTemplate').html();
                var template = Handlebars.compile(renderTemplate);
                var result = template(json.data);
                $list.html(result);
                $('img').lazyload();
            } else {
                $list.html('<li class="no-result">没有合适的搜索结果喔~</li>');
            }
        } else {}
    }

    function initPlacePage() {

        CT.util.Request(cityName, CT.app.renderList);

    }

}());